<template>
  <view class="nav-header" :style="{ paddingTop: statusBarHeight + 'px' }">    
    <!-- 导航栏主体 -->
    <view class="nav-bar" :style="{ height: navBarHeight + 'px' }">
      <!-- 左侧内容 -->
      <view class="left-content" @click="handleLeftClick">
        <slot name="left">
          <!-- 默认返回按钮 -->
          <view v-if="showBack" class="back-btn">
            <uni-icons type="back" size="22" color="#333"></uni-icons>
            <text v-if="backText" class="back-text">{{ backText }}</text>
          </view>
        </slot>
      </view>
      
      <!-- 标题 -->
      <view class="title-container">
        <text class="title" :style="{ color: titleColor }">{{ title }}</text>
      </view>
      
      <!-- 右侧内容 -->
      <view class="right-content">
        <slot name="right"></slot>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  titleColor: {
    type: String,
    default: '#333'
  },
  showBack: {
    type: Boolean,
    default: true
  },
  backText: {
    type: String,
    default: ''
  },
  customBack: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['back'])

// 状态栏和导航栏高度
const statusBarHeight = ref(0)
const navBarHeight = ref(42) // 默认导航栏高度

onMounted(() => {
  uni.getSystemInfo({
    success: (res) => {
      //safeAreaInsets 获取屏幕边界到安全区域距离
      statusBarHeight.value = res.statusBarHeight
      if (res.platform === 'ios' || res.platform === 'android') {
        navBarHeight.value = 40
      }
    }
  })
})

const handleLeftClick = () => {
  if (props.customBack) {
    emit('back')
    return
  }

  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.switchTab({
      url: '/pages/index/index'
    })
  }
}
</script>

<style lang="scss" scoped>
.nav-header {
  position: relative;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);

  .nav-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
    height: 44px;
  }

  .title {
    font-size: 16px;
    color: #333;
  }

  .back-btn {
    display: flex;
    align-items: center;

    .back-text {
      margin-left: 5px;
      font-size: 16px;
      color: #333;
    }
  }
}
</style>